var util = require('../../../utils/util.js');
var check = require('../../../utils/check.js');
var api = require('../../../config/api.js');

var app = getApp();

Page({
  data: {
    // array: ['请选择反馈类型', '商品相关', '功能异常', '优化建议', '其他'],
    feedbackTypeList:[],
    index: 0,
    content: '',  
    contentLength: 0,
    hasPicture: false,
    picUrls: [],
    files: [],
    allBrandList: [],
    brandIndex:0,
    allCategoryList: [],
    categoryIndex:0,
    currentCategoryList: [],
    productName:"",
    currentPrice:0,
    productCount:1,
    productUnit:"件",
    attrName:""
  },  
  chooseImage: function(e) {
    if (this.data.files.length >= 5) {
      util.showErrorToast('只能上传五张图片')
      return false;
    }

    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
        that.upload(res);
      }
    })
  },
  upload: function(res) {
    var that = this;
      const uploadTask = wx.uploadFile({
      url: api.UploadBuyFiles,
      filePath: res.tempFilePaths[0],
      name: 'file',
      header: {
        //'Content-Type': 'application/json',
        'content-type': 'application/x-www-form-urlencoded',
        //'X-Litemall-Token': wx.getStorageSync('token')
        'X-fjb-Token': wx.getStorageSync('token')
      },
      success: function(res) {
        console.log(res);
        var _res = JSON.parse(res.data); 
        if (_res.code === 200) {  
          var url = _res.dataObject.newFileName;
          that.data.picUrls.push(url)
          that.setData({
            hasPicture: true,
            picUrls: that.data.picUrls
          })
        }else{  
          wx.showToast({   
            title: _res.msg,
            icon: 'none',
            duration: 2000
          })
        } 
      },
      fail: function(e) {
        wx.showModal({
          title: '错误',
          content: '上传失败',
          showCancel: false
        })
      },
    })
    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  bindPickerChange: function(e) { 
    this.setData({
      index: e.detail.value
    });
  },
  bindBrandPickerChange: function(e) {
    let _allCategoryList = this.data.allCategoryList;
    // 当前品牌索引 
    let _brandIndex = e.detail.value;
    // 得到品牌id
    let _brandId = this.data.allBrandList[_brandIndex].id;

    var _currentCategoryList = [];
    var categoryObj = {
      id:0,
      brandId:0,  
      categoryName:"车型" 
    }  
    _currentCategoryList.push(categoryObj);
    for (let idex = 0; idex < _allCategoryList.length; idex++) {
      const element = _allCategoryList[idex];
      if(element.brandId==_brandId){
        _currentCategoryList.push(element);
      }
    }

    this.setData({
      brandIndex: _brandIndex,
      currentCategoryList:_currentCategoryList,
      categoryIndex: 0
    });
  },
  bindCategoryPickerChange: function(e) {
    this.setData({
      categoryIndex: e.detail.value
    });
  },
  contentInput: function(e) {
    this.setData({
      contentLength: e.detail.cursor,
      content: e.detail.value,
    });
  },
  inputProductName: function(e) {
    this.setData({
      productName: e.detail.value,
    });
  },  
  inputCurrentPrice: function(e) {
    this.setData({
      currentPrice: e.detail.value,
    });
  },
  inputProductCount: function(e) {
    this.setData({
      productCount: e.detail.value,
    });
  },
  inputProductUnit: function(e) {
    this.setData({
      productUnit: e.detail.value,
    });
  },
  inputAttrName: function(e) {
    this.setData({
      attrName: e.detail.value,
    });
  },

  submitRecycleInfo: function(e) {
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }

    let that = this;
    let _brandIndex = that.data.brandIndex;
    if (_brandIndex == 0) {
      util.showErrorToast('请选择品牌');
      return false;
    }

    let _categoryIndex = that.data.categoryIndex;
    if (_categoryIndex == 0) {
      util.showErrorToast('请选择车型');
      return false;
    }

    if (that.data.content == '') {
      util.showErrorToast('请输入反馈内容');
      return false;
    }
    
    var _productName = that.data.productName;
    if (_productName == '') {
      util.showErrorToast('请输入产品名称');
      return false;
    }

    var _currentPrice = that.data.currentPrice;
    if (_currentPrice == '') {
      util.showErrorToast('请输入价格');
      return false;
    }

    var _productCount = that.data.productCount;
    if (_productCount == '') {
      util.showErrorToast('请输入数量');
      return false;
    }

    var _productUnit = that.data.productUnit;
    if (_productUnit == '') {
      util.showErrorToast('请输入数量单位');
      return false;
    }

    var _attrName = that.data.attrName;
    if (_attrName == '') {
      util.showErrorToast('请输入属性名称');
      return false;
    }

    wx.showLoading({
      title: '提交中...',
      mask: true,
      success: function() {
      }
    });

    util.request(api.RecycleAddInfo, {
      dealType:2,
      brandId:that.data.allBrandList[_brandIndex].id,
      categoryId:that.data.currentCategoryList[_categoryIndex].id,
      productName:_productName,
      productDetails: that.data.content,
      currentPrice:_currentPrice,
      productCount:_productCount,
      productUnit:_productUnit,
      attrName:_attrName, 
      productFiles: that.data.picUrls
    }, 'POST').then(function(res) {
      wx.hideLoading();
      if (res.code === 200) {
        wx.showToast({
          title: '发布收购成功',
          icon: 'success',
          duration: 2000,
          complete: function() {
            that.setData({
              index: 0,
              content: '',
              contentLength: 0,
              brandIndex:0,
              categoryIndex:0,
              productName:"",
              currentPrice:0,
              productCount:1,
              productUnit:"件",
              attrName:"",
              hasPicture: false,
              picUrls: [],
              files: []
            });
          }
        });
      } else {
        util.showErrorToast(res.errmsg);
      }

    });
  },  
  onLoad: function(options) {

  },
  onReady: function() {
    wx.showLoading({
      title: '加载中...',
    });
    this.getBrandCategoryList();  
  },
  onShow: function() {
        
  },
  getBrandCategoryList: function() {
    let that = this;
    var _currentCategoryList = [];
    var categoryObj = {
      id:0,
      brandId:0,  
      categoryName:"车型"
    }   
    _currentCategoryList.push(categoryObj);
    util.request(api.GetBrandCategoryList).then(function(res) {
      if (res.code === 200) {
        that.setData({
          allBrandList: res.dataObject.allBrandList,
          allCategoryList: res.dataObject.allCategoryList,
          currentCategoryList:_currentCategoryList,
        });
      }
      wx.hideLoading();
    });
  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭
  }
})